package com.mediacloud.app.newsmodule.service;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.mediacloud.app.user.net.SSLSocketClient;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.loopj.android.http.RequestParams;
import com.mediacloud.app.assembly.common.MD5Encoder;
import com.mediacloud.app.assembly.interfaces.LoadNetworkBack;
import com.mediacloud.app.newsmodule.drama.DramaVideoHelper;
import com.mediacloud.app.newsmodule.model.DownLoad;
import com.mediacloud.app.newsmodule.model.OnDownloadProcessListener;
import com.mediacloud.app.newsmodule.utils.DownloadDB;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.reslib.util.RequestParamsX;

import org.apache.http.conn.ssl.SSLSocketFactory;

import java.io.File;
import java.util.ArrayList;

public class DownloadManager {

    ArrayList<DownLoad> mQueue = new ArrayList<DownLoad>();
    DownloadDB mDownloadDB;
    OnDownloadProcessListener mOnDownloadProcessListener;
    Context mContext;
    private static DownloadManager mDownloadManager;

    public static DownloadManager getInstace() {
        if (mDownloadManager == null) {
            mDownloadManager = new DownloadManager();
        }

        return mDownloadManager;
    }

    public void setOnDownloadProcessListener(OnDownloadProcessListener listener) {

        mOnDownloadProcessListener = listener;
    }


    public void onStartCommand(Context context) {
        mContext = context;
        mDownloadDB = new DownloadDB(mContext);
        http = new HttpUtils();
        http.configRequestThreadPoolSize(5);
        ArrayList<DownLoad> data = mDownloadDB.getDownLoadData(DownloadDB.ING_TABLE_NAME_);
        if (data != null) {
            mQueue.addAll(data);
        }
        toDownLoad();
    }

    public void toDownLoad() {

        if(handler!=null)
        {
            //Log.i("test","onProcess:handler.isPase?"+handler.isPaused() +"   handler.isCancel:"+handler.isCancelled());
          /*  if(!handler.isPaused())
            {
                return;
            }*/

        }
        if (mQueue.size() > 0) {
            if (mQueue.get(0).getTypes().equals("0")) {
                getViedeoInfo(mQueue.get(0).getUrl(), mQueue.get(0).getTagId());
            } else {
                dowloadQueue(mQueue.get(0));
            }
        }
    }

    private void getViedeoInfo(String article_id, String catalog_id) {
        String interfaces = "api/content/drama-info";
        RequestParams param = new RequestParamsX();
        param.put("article_id", article_id);
        param.put("catalog_id", catalog_id);

//        param.put("api_version", "1.2.3");
        HTTPClient helper = new HTTPClient();
        helper.getNetData(new LoadNetworkBack<DramaVideoHelper>() {

            @Override
            public void Success(DramaVideoHelper result) {


                if (result.mUrls == null||!result.state) {
                    mQueue.get(0).setTagId("-1");
                    mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                    mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                    mQueue.remove(0);
                    if(mOnDownloadProcessListener!=null) {
                        mOnDownloadProcessListener.onProcess("-1", 111, 111, null);
                    }
                    toDownLoad();


                    return;
                }
                //Log.i("test", "result.mUrls.mp4Address.size():" + result.mUrls.mp4Address.size());
                if (result.mUrls.mp4Address.size() != 0&&mQueue.size()!=0) {

                    int rate = Integer.parseInt(mQueue.get(0).getRate());
                    if (result.mUrls.mp4Address.size() > (rate + 1)&&mQueue.size()>0) {
                        mQueue.get(0).setUrl(result.mUrls.mp4Address.get(rate).url);
                        mQueue.get(0).setTypes("1");
                        mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        mDownloadDB.saveData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        dowloadQueue(mQueue.get(0));
                    } else {


                        mQueue.get(0).setUrl(result.mUrls.mp4Address.get(result.mUrls.mp4Address.size() - 1).url);
                        mQueue.get(0).setTypes("1");
                        mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        mDownloadDB.saveData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        dowloadQueue(mQueue.get(0));
                    }
                } else {

                    if(mQueue.size()>0) {
                        mQueue.get(0).setTagId("-1");
                        mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                        mQueue.remove(0);

                    }else
                    {

                    }
                    if(mOnDownloadProcessListener!=null) {
                        mOnDownloadProcessListener.onProcess("-1", 111, 111, null);
                    }
                    toDownLoad();

                }
            }

            @Override
            public void Failure(Object obj) {

            }

            @Override
            public void otherData(String result) {

            }
        }, DataInvokeUtil.ServerURL + interfaces, new DramaVideoHelper(), param);
    }

    public void addQueue(DownLoad item) {
        //Log.i("test", "mDownloadDB:" + mDownloadDB);
        //Log.i("test", "item:" + item);

        if (mDownloadDB == null) {
            mDownloadDB = new DownloadDB(mContext);
        }
        mDownloadDB.saveData(item, DownloadDB.ING_TABLE_NAME_);
        mQueue.add(item);

        if (mQueue.size() == 1) {
            toDownLoad();
        }


    }

    public void addQueues(ArrayList<DownLoad> datas) {

        if (mDownloadDB == null) {
            mDownloadDB = new DownloadDB(mContext);
        }
        for (int i = 0; i < datas.size(); i++) {
            mDownloadDB.saveData(datas.get(i), DownloadDB.ING_TABLE_NAME_);
        }
        mQueue.addAll(datas);
        if (mQueue.size() == 1) {
            toDownLoad();
        }
    }
    public HttpHandler handler;
    HttpUtils http;
    private void dowloadQueue(DownLoad item) {


        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/appfactory/videocach/" + MD5Encoder.encode(item.getUrl()) + ".mp4";

       /* File file = new File(sdPath);
        if (file.exists()) {
            file.delete();
        }*/

       http.configSSLSocketFactory(SSLSocketFactory.getSocketFactory());
        handler = http.download(item.getUrl(), sdPath, true, false, new RequestCallBack<File>() {

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                // TODO Auto-generated method stub
                super.onLoading(total, current, isUploading);
                try {
                    if (mOnDownloadProcessListener != null && mQueue.size() > 0) {
                        mOnDownloadProcessListener.onProcess(mQueue.get(0).getId(), total, current, null);
                    }else
                    {
                        handler.cancel();
                        handler=null;
                        http=null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onSuccess(ResponseInfo<File> arg0) {
                // TODO Auto-generated method stub
                if (mQueue.size() > 0) {
                    mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                    mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                    mQueue.remove(0);
                    if(mOnDownloadProcessListener!=null) {
                        mOnDownloadProcessListener.onProcess("-1", 111, 111, null);
                    }
                    toDownLoad();

                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                if (mQueue.size() > 0) {
                    if (arg0.getExceptionCode() >= 400 && arg0.getExceptionCode() <= 404) {
                        mQueue.get(0).setTagId("-2");
                        mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                        mQueue.remove(0);
                        if(mOnDownloadProcessListener!=null) {
                            mOnDownloadProcessListener.onProcess("-1", 111, 111, null);
                        }
                        toDownLoad();
                    }

                }else
                {
                    handler.cancel();
                    handler=null;
                    http=null;
                }


            }
        });

    }
    public  void  cancelDownload()
    {
        handler.cancel();
        handler=null;

        http=null;
    }

    public void deleteIngDown(int position)
    {
        //Log.i("test","onProcess:ing:position==>"+position+"   mQueue  size: "+mQueue.size());
        mDownloadDB.deleteData(mQueue.get(position), DownloadDB.ING_TABLE_NAME_);

        if(position==0&&handler!=null)
        {
            handler.cancel();
        }
        mQueue.remove(position);
     //   toDownLoad();
    }
    private void checkQuenIsNull() {

        if (mQueue.size() < 1) {
            mQueue.addAll(mDownloadDB.getDownLoadData(DownloadDB.ING_TABLE_NAME_));
        }

    }

}